package flc.ast.fragment;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.bigkoo.pickerview.utils.LunarCalendar;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.contrarywind.adapter.WheelAdapter;
import com.contrarywind.view.WheelView;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import flc.ast.R;
import flc.ast.activity.AddOvertimeActivity;
import flc.ast.activity.AddWorkTimeActivity;
import flc.ast.adapter.CalendarAdapter;
import flc.ast.adapter.WorkTimeAdapter;
import flc.ast.bean.MyCalendarBean;
import flc.ast.bean.OvertimeBean;
import flc.ast.bean.OvertimeRecordBean;
import flc.ast.bean.WorkTimeBean;
import flc.ast.databinding.FragmentWorkTimeBinding;
import flc.ast.utils.MyDatabase;
import flc.ast.utils.MyRecordLoader;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link WorkTimeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class WorkTimeFragment extends BaseNoModelFragment<FragmentWorkTimeBinding> {

    private Dialog mySelMonthDialog;
    private WheelView wheelView1, wheelView2;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
    private String formatStr = "%.1f";
    private int year, month;
    private CalendarAdapter calendarAdapter;
    private int oldPosition = 0;
    private String selDate = "";
    private WorkTimeAdapter workTimeAdapter;

    @Override
    protected int onCreate() {
        return R.layout.fragment_work_time;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.tvDate.setOnClickListener(this);
        mDataBinding.ivAdd.setOnClickListener(this);
        mDataBinding.ivLast.setOnClickListener(this);
        mDataBinding.ivNext.setOnClickListener(this);

        mDataBinding.rvCalendarList.setLayoutManager(new GridLayoutManager(mContext, 7));
        calendarAdapter = new CalendarAdapter();
        mDataBinding.rvCalendarList.setAdapter(calendarAdapter);
        calendarAdapter.setOnItemClickListener(this);

        mDataBinding.rvWorkTimeList.setLayoutManager(new LinearLayoutManager(mContext));
        workTimeAdapter = new WorkTimeAdapter();
        mDataBinding.rvWorkTimeList.setAdapter(workTimeAdapter);
        workTimeAdapter.setOnItemClickListener(this);

        //选择月份弹框
        selMonthDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivLast://上一月
                if (month == 1) {
                    month = 12;
                    year--;
                } else {
                    month--;
                }
                if (month < 10) {
                    mDataBinding.tvDate.setText(year + ".0" + month);
                } else {
                    mDataBinding.tvDate.setText(year + "." + month);
                }
                getData();
                setDay(month, year);//设置日历
                break;
            case R.id.ivNext://下一月
                if (month == 12) {
                    month = 1;
                    year++;
                } else {
                    month++;
                }
                if (month < 10) {
                    mDataBinding.tvDate.setText(year + ".0" + month);
                } else {
                    mDataBinding.tvDate.setText(year + "." + month);
                }
                getData();
                setDay(month, year);//设置日历
                break;
            case R.id.tvDate://月份
                mySelMonthDialog.show();
                break;
            case R.id.ivAdd://添加
                AddWorkTimeActivity.workTimeBean = null;
                startActivity(AddWorkTimeActivity.class);
                break;
            //选择日期弹框
            case R.id.ivDialogSelMonthCancel://取消
                mySelMonthDialog.dismiss();
                break;
            case R.id.ivDialogSelMonthRight://确定
                mySelMonthDialog.dismiss();
                int y = wheelView1.getCurrentItem() + 1980;
                int moon = wheelView2.getCurrentItem() + 1;
                String date = y + "-" + (moon < 10 ? "0" + moon : moon);
                mDataBinding.tvDate.setText(date);
                year = y;
                month = moon;
                getData();
                setDay(month, year);//设置日历
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == calendarAdapter) {
            if (TextUtils.isEmpty(calendarAdapter.getItem(position).getDate1())) return;
            calendarAdapter.getItem(oldPosition).setSelect(false);
            calendarAdapter.notifyItemChanged(oldPosition);
            oldPosition = position;
            calendarAdapter.getItem(position).setSelect(true);
            calendarAdapter.notifyItemChanged(position);
            selDate = calendarAdapter.getItem(position).getDate();
            getWorkTimeData();
        } else if (adapter == workTimeAdapter) {
            AddWorkTimeActivity.workTimeBean = workTimeAdapter.getItem(position);
            startActivity(AddWorkTimeActivity.class);
        }
    }

    @Override
    protected void initData() {
        mDataBinding.tvDate.setText(TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM")));
        year = Integer.parseInt(TimeUtils.getNowString(new SimpleDateFormat("yyyy")));//获取当前年份
        month = Integer.parseInt(TimeUtils.getNowString(new SimpleDateFormat("M")));//获取当前月份
        setDay(month, year);//设置日历
        //默认选中显示今天的日期记录
        setShowNowDay(year + "." + month + ".");
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
        getWorkTimeData();
        calendarAdapter.notifyDataSetChanged();
    }

    private void getData() {
        String startDate = year + "." + month + ".01";
        String endDate = "";
        if (month == 12) {
            endDate = (year + 1) + ".01.01";
        } else {
            endDate = year + "." + (month + 1) + ".01";
        }
        long startTime = TimeUtils.string2Millis(startDate, new SimpleDateFormat("yyyy.MM.dd"));
        long endTime = TimeUtils.string2Millis(endDate, new SimpleDateFormat("yyyy.MM.dd"));
        //每月加班
        double duration = 0;
        double income = 0;
        List<WorkTimeBean> monthTime = MyDatabase.getInstance(mContext).getWorkTimeDao().getMonthWorkTime(startTime, endTime);

        if (monthTime.size() == 0) {
            mDataBinding.tvIncome.setText("0");
            mDataBinding.tvOvertimeHours.setText("0");
            mDataBinding.tvWorkTimeIncome.setText("0");
            mDataBinding.tvRecordDays.setText("0");

        } else {
            for (WorkTimeBean workTimeBean : monthTime) {
                duration += workTimeBean.getDuration();
                income += workTimeBean.getIncome();
            }
            mDataBinding.tvIncome.setText(String.format(formatStr, income));
            mDataBinding.tvOvertimeHours.setText(String.format(formatStr, duration));
            mDataBinding.tvWorkTimeIncome.setText(String.format(formatStr, income));
            int num = 0;

            //记录天数
            Map<String, List<WorkTimeBean>> timeCategoryMap = new HashMap<>();
            for (WorkTimeBean workTimeBean : monthTime) {
                String time = TimeUtils.millis2String(workTimeBean.getDate(), "MM-dd EEEE");

                List<WorkTimeBean> beanList = null;
                if (timeCategoryMap.containsKey(time)) {
                    beanList = timeCategoryMap.get(time);
                } else {
                    beanList = new ArrayList<>();
                    timeCategoryMap.put(time, beanList);
                }

                beanList.add(workTimeBean);
            }
            Iterator<String> iterator = timeCategoryMap.keySet().iterator();
            String time = null;
            while (iterator.hasNext()) {
                time = iterator.next();
                num++;
            }
            mDataBinding.tvRecordDays.setText(String.valueOf(num));
        }
    }

    private void getWorkTimeData() {
        long date = TimeUtils.string2Millis(selDate, new SimpleDateFormat("yyyy年MM月dd日"));
        List<WorkTimeBean> todayTime = MyDatabase.getInstance(mContext).getWorkTimeDao().getTodayWorkTime(date);

        if (todayTime.size() == 0) {
            mDataBinding.rvWorkTimeList.setVisibility(View.GONE);
        } else {
            workTimeAdapter.setList(todayTime);
            mDataBinding.rvWorkTimeList.setVisibility(View.VISIBLE);
        }
    }

    //设置日期数据
    private void setDay(int moon, int year) {
        //获取天数
        int dayNum = getDayNum(moon);
        //获取需要空出的天数
        int weekNum = getWeekNum(moon, year);
        //获取农历偏移量
        LunarCalendar lunarCalendar = new LunarCalendar();
        //生成日历表
        List<MyCalendarBean> listDay = new ArrayList<>();
        for (int i = 0; i < 42; i++) {
            if (i <= weekNum || i > dayNum + weekNum) {
                listDay.add(new MyCalendarBean("", "", "", i, false, false));//空
            } else {
                int day = i - weekNum;
                String date = year + "年" + (moon < 10 ? "0" + moon : moon) + "月" + (day < 10 ? "0" + day : day) + "日";
                int[] offset = lunarCalendar.solarToLunar(year, moon, i - weekNum);
                listDay.add(new MyCalendarBean(i - weekNum + "", getChinaDayString(offset[2]), date, i, false, false));
            }
        }
        calendarAdapter.setList(listDay);
    }

    //判断该月有多少天
    private int getDayNum(int moon) {
        int dayNum = 31;
        if (moon == 1 || moon == 3 || moon == 5 || moon == 7 || moon == 8 || moon == 10 || moon == 12) {
            //大月31天
            dayNum = 31;
        } else if (moon == 2) {
            //2月判断是闰(29)还是平(28)
            if (TimeUtils.isLeapYear(TimeUtils.getNowString(format), format)) {
                dayNum = 29;
            } else {
                dayNum = 28;
            }
        } else {
            //小月30天
            dayNum = 30;
        }
        return dayNum;
    }

    //获取该月第一天是星期几（当天要算上 所以少减一天）
    private int getWeekNum(int moon, int year) {
        int weekNum = 0;
        String week = TimeUtils.getChineseWeek(year + "." + moon + ".01", format);
        if (week.equals(getString(R.string.monday_text))) {
            weekNum = 0;
        } else if (week.equals(getString(R.string.tuesday_text))) {
            weekNum = 1;
        } else if (week.equals(getString(R.string.wednesday_text))) {
            weekNum = 2;
        } else if (week.equals(getString(R.string.thursday_text))) {
            weekNum = 3;
        } else if (week.equals(getString(R.string.friday_text))) {
            weekNum = 4;
        } else if (week.equals(getString(R.string.saturday_text))) {
            weekNum = 5;
        } else if (week.equals(getString(R.string.sunday_text))) {
            weekNum = 6;
        }
        return weekNum;
    }

    //转农历
    public static String getChinaDayString(int day) {
        String chineseTen[] = {"初", "十", "廿", "三"};
        String chineseDay[] = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十"};
        String var = "";
        if (day != 20 && day != 30) {
            var = chineseTen[(int) ((day - 1) / 10)] + chineseDay[(int) ((day - 1) % 10)];
        } else if (day != 20) {
            var = chineseTen[(int) (day / 10)] + "十";
        } else {
            var = "二十";
        }
        return var;
    }

    //显示今天
    private void setShowNowDay(String date) {
        for (MyCalendarBean bean : calendarAdapter.getValidData()) {
            if (!TextUtils.isEmpty(bean.getDate1())) {
                String nowDate = date + bean.getDate1();
                if (nowDate.equals(TimeUtils.getNowString(new SimpleDateFormat("yyyy.M.d")))) {
                    oldPosition = bean.getPos();
                    selDate = bean.getDate();
                    bean.setSelect(true);
                    break;
                }
            }
        }
        calendarAdapter.notifyDataSetChanged();
    }

    //选择月份弹框
    private void selMonthDialog() {
        mySelMonthDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_month, null);
        mySelMonthDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mySelMonthDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        lp.width = (int) (dm.widthPixels * 1);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView dialogCancel = inflate.findViewById(R.id.ivDialogSelMonthCancel);
        ImageView dialogRight = inflate.findViewById(R.id.ivDialogSelMonthRight);
        wheelView1 = inflate.findViewById(R.id.wheel_view1);
        wheelView2 = inflate.findViewById(R.id.wheel_view2);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
        wheelView1.setDividerColor(Color.parseColor("#2E979797"));
        wheelView1.setTextColorCenter(Color.parseColor("#000000"));
        wheelView1.setLineSpacingMultiplier(2.5f);
        wheelView1.setDividerType(WheelView.DividerType.WRAP);
        wheelView1.setCurrentItem(43);
        wheelView1.setItemsVisibleCount(5);
        wheelView1.setCyclic(true);
        wheelView1.setTextSize(15);
        wheelView2.setDividerColor(Color.parseColor("#2E979797"));
        wheelView2.setTextColorCenter(Color.parseColor("#000000"));
        wheelView2.setLineSpacingMultiplier(2.5f);
        wheelView2.setDividerType(WheelView.DividerType.WRAP);
        wheelView2.setCurrentItem(0);
        wheelView2.setItemsVisibleCount(5);
        wheelView2.setCyclic(true);
        wheelView2.setTextSize(15);
        //设置滚轮数据
        List<String> listYear = new ArrayList<>();//年 1980-2040
        for (int i = 0; i < 61; i++) {
            listYear.add(String.valueOf(1980 + i));
        }
        List<String> listMonth = new ArrayList<>();//月 12
        for (int i = 0; i < 12; i++) {
            listMonth.add(String.valueOf((i + 1) < 10 ? "0" + (i + 1) : i + 1));
        }
        WheelAdapter adapter1 = new ArrayWheelAdapter(listYear);
        wheelView1.setAdapter(adapter1);
        WheelAdapter adapter2 = new ArrayWheelAdapter(listMonth);
        wheelView2.setAdapter(adapter2);

        //滚动到对应日期
        String date = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
        String[] split = date.split("-");
        int year = Integer.parseInt(split[0]);//年
        int moon = Integer.parseInt(split[1]);//月
        wheelView1.setCurrentItem(year - 1980);
        wheelView2.setCurrentItem(moon - 1);
    }

}